package com.maple.common.utils

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.maple.common.R
import com.maple.common.base.BaseQuickBindAdapter
import com.maple.common.base.BaseViewHolder
import com.maple.common.databinding.WidgetBottomSheetBinding
import com.maple.common.databinding.WidgetTimePickerBinding
import com.maple.common.entity.BottomSheetEntity
import com.maple.common.ext.click
import com.maple.common.ext.divider
import com.maple.common.ext.gone
import com.maple.common.ext.visible
import com.maple.common.widget.wheel.OnValueChangeListener
import com.maple.common.widget.wheel.TimeWheelAdapter
import com.maple.common.widget.wheel.WheelView
import java.util.Calendar


/**
 * Tip:
 * Create by SeVen on 2024/3/21 19:28
 */
object BottomSheetUtils {
    fun showBottomSheet(
        context: Context,
        titleContent: String? = null,
        entity: MutableList<BottomSheetEntity>? = null,
        onBottomSheetClickListener: ((BottomSheetEntity) -> Unit)? = null
    ) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
//        bottomSheetDialog.setCancelable(false)
        val binding = WidgetBottomSheetBinding.bind(
            LayoutInflater.from(context).inflate(R.layout.widget_bottom_sheet, null)
        )
        binding.btnCancel.click {
            bottomSheetDialog.dismiss()
        }
        titleContent?.let {
            binding.tvSheetTitle.text = titleContent
            binding.llTitleLayer.visible()
        } ?: kotlin.run {
            binding.llTitleLayer.gone()
        }
        val bottomSheetAdapter = BottomSheetAdapter()
        binding.sheetRecycle.apply {
            layoutManager = LinearLayoutManager(context)
            divider(Color.parseColor("#F2F2F2"), size = 1)
            adapter = bottomSheetAdapter
        }
        bottomSheetAdapter.submitList(entity)
        bottomSheetAdapter.setOnItemClickListener { adapter, _, position ->
            adapter.getItem(position)?.let { onBottomSheetClickListener?.invoke(it) }
            bottomSheetDialog.dismiss()
        }
        bottomSheetDialog.setContentView(binding.root)
        //设置点击dialog外部不消失
        //bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show()
    }

    fun <T : Any, VH : RecyclerView.ViewHolder> showBottomSheet(
        context: Context,
        titleContent: String? = null,
        bottomSheetAdapter: BaseQuickBindAdapter<T, VH>,
        sheetList: MutableList<T>?,
        onBottomSheetClickListener: ((T) -> Unit)? = null
    ) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog.setCancelable(false)
        val binding = WidgetBottomSheetBinding.bind(
            LayoutInflater.from(context).inflate(R.layout.widget_bottom_sheet, null)
        )
        binding.btnCancel.click {
            bottomSheetDialog.dismiss()
        }
        titleContent?.let {
            binding.tvSheetTitle.text = titleContent
            binding.llTitleLayer.visible()
        } ?: kotlin.run {
            binding.llTitleLayer.gone()
        }
        binding.sheetRecycle.apply {
            layoutManager = LinearLayoutManager(context)
            divider(Color.parseColor("#F2F2F2"), size = 1)
            adapter = bottomSheetAdapter
        }
        bottomSheetAdapter.submitList(sheetList)
        bottomSheetAdapter.setOnItemClickListener { adapter, _, position ->
            adapter.getItem(position)?.let { onBottomSheetClickListener?.invoke(it) }
            bottomSheetDialog.dismiss()
        }
        bottomSheetDialog.setContentView(binding.root)
        //设置点击dialog外部不消失
        //bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show()
    }

    fun <T : Any> showBottomSheet(
        context: Context,
        titleContent: String? = null,
        bottomSheetAdapter: BaseQuickBindAdapter<T, QuickViewHolder>
    ): BottomSheetDialog {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        val binding = WidgetBottomSheetBinding.bind(
            LayoutInflater.from(context).inflate(R.layout.widget_bottom_sheet, null)
        )
        binding.btnCancel.click {
            bottomSheetDialog.dismiss()
        }
        titleContent?.let {
            binding.tvSheetTitle.text = titleContent
            binding.tvSheetTitle.visible()
        } ?: kotlin.run {
            binding.tvSheetTitle.gone()
        }
        binding.sheetRecycle.apply {
            layoutManager = LinearLayoutManager(context)
            divider(Color.parseColor("#F2F2F2"), size = 1)
            adapter = bottomSheetAdapter
        }
        bottomSheetDialog.setContentView(binding.root)
        //设置点击dialog外部不消失
        //bottomSheetDialog.setCanceledOnTouchOutside(false);
        return bottomSheetDialog
    }

    fun showTimePicker(
        context: Context,
        formatType: String,
        selectYear: Int? = null,
        selectMonth: Int? = null,
        selectDay: Int? = null,
        selectHour: Int? = null,
        selectMinute: Int? = null,
        onBottomSheetClickListener: ((String?) -> Unit)? = null
    ) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        val binding = WidgetTimePickerBinding.bind(
            LayoutInflater.from(context).inflate(R.layout.widget_time_picker, null)
        )
        bottomSheetDialog.setCancelable(false)
        bottomSheetDialog.setContentView(binding.root)
        binding.btnCancel.click {
            bottomSheetDialog.dismiss()
        }
        binding.btnSure.click {
            val year = binding.yearPicker.getCurrentItem()
            val month = binding.monthPicker.getCurrentItem()
            val day = binding.dayPicker.getCurrentItem()
            val hour = binding.hourPicker.getCurrentItem()
            val minute = binding.minutePicker.getCurrentItem()
            val time = DateUtils.stringToString(
                "$year$month$day $hour$minute",
                "yyyy年MM月dd日 HH时mm分",
                formatType
            )
            onBottomSheetClickListener?.invoke(time)
            bottomSheetDialog.dismiss()
        }
        binding.tvTitle.text = "选择时间"

        val calendar = Calendar.getInstance()
        // 年
        val yearNow = calendar.get(Calendar.YEAR)
        val yearNum = mutableListOf<Int>()
        for (i in 0 until 10) {
            yearNum.add(yearNow + i * 1)
        }
        binding.yearPicker.setAdapter(TimeWheelAdapter(yearNum, "年"))
        binding.yearPicker.setMaxValue(9)
        binding.yearPicker.setMinValue(0)
        selectYear?.and(selectMonth!!)?.and(selectDay!!)?.let {
            binding.yearPicker.setValue("$selectYear")
        } ?: kotlin.run {
            binding.yearPicker.setValue("$yearNow")
        }


        // 月
        val newMonth = calendar.get(Calendar.MONTH) + 1
        val monthNum = mutableListOf<Int>()
        for (i in 1..12) {
            monthNum.add(i)
        }
        binding.monthPicker.setAdapter(TimeWheelAdapter(monthNum, "月"))
        binding.monthPicker.setMinValue(0)
        binding.monthPicker.setMaxValue(11)
        selectYear?.and(selectMonth!!)?.and(selectDay!!)?.let {
            binding.monthPicker.setValue("$selectMonth")
        } ?: kotlin.run {
            binding.monthPicker.setValue("$newMonth")
        }

        // 日
        binding.dayPicker.setMinValue(0)
        var maxValue = 0
        selectYear?.and(selectMonth!!)?.and(selectDay!!)?.let {
            val selCalendar = Calendar.getInstance()
            selCalendar.set(Calendar.YEAR, selectYear)
            selCalendar.set(Calendar.MONTH, selectMonth)
            selCalendar.set(Calendar.DATE, 1)
            selCalendar.roll(Calendar.DATE, -1)
            maxValue = selCalendar.get(Calendar.DATE)
            val updateDays = mutableListOf<Int>()
            for (i in 1..maxValue) {
                updateDays.add(i)
            }
            binding.dayPicker.setAdapter(TimeWheelAdapter(updateDays, "日"))
            binding.dayPicker.setMaxValue(maxValue - 1)
            binding.dayPicker.setValue("$selectDay")
        } ?: kotlin.run {
            val newDay = calendar.get(Calendar.DAY_OF_MONTH)
            maxValue = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
            val dayList = mutableListOf<Int>()
            for (i in 1..maxValue) {
                dayList.add(i)
            }
            binding.dayPicker.setAdapter(TimeWheelAdapter(dayList, "日"))
            binding.dayPicker.setMaxValue(maxValue - 1)
            binding.dayPicker.setValue("$newDay")
        }

        //时
        val newHour = calendar.get(Calendar.HOUR_OF_DAY)
        val hourNum = mutableListOf<Int>()
        for (i in 0..24) {
            hourNum.add(i)
        }
        binding.hourPicker.setAdapter(TimeWheelAdapter(hourNum, "时"))
        binding.hourPicker.setMinValue(0)
        binding.hourPicker.setMaxValue(23)
        selectHour?.and(selectMonth!!)?.and(selectDay!!)?.let {
            binding.hourPicker.setValue("$selectMonth")
        } ?: kotlin.run {
            binding.hourPicker.setValue("$newHour")
        }
        //分
        val newMinute = calendar.get(Calendar.MINUTE)
        val minuteNum = mutableListOf<Int>()
        for (i in 0 until 60) {
            minuteNum.add(i)
        }
        binding.minutePicker.setAdapter(TimeWheelAdapter(minuteNum, "分"))
        binding.minutePicker.setMinValue(0)
        binding.minutePicker.setMaxValue(59)
        selectMinute?.let {
            binding.minutePicker.setValue("$selectMinute")
        } ?: kotlin.run {
            binding.minutePicker.setValue("$newMinute")
        }

        binding.yearPicker.setOnValueChangedListener(object : OnValueChangeListener {
            override fun onValueChange(picker: WheelView, oldVal: String, newVal: String) {
                val year = binding.yearPicker.getCurrentItem()
                val month = binding.monthPicker.getCurrentItem()
                val day = binding.dayPicker.getCurrentItem()
                val selCalendar = Calendar.getInstance()
                selCalendar.set(Calendar.YEAR, year.substring(0, year.length - 1).toInt())
                selCalendar.set(Calendar.MONTH, month.substring(0, month.length - 1).toInt() - 1)
                selCalendar.set(Calendar.DATE, 1)
                selCalendar.roll(Calendar.DATE, -1)
                val date = selCalendar.get(Calendar.DATE)
                val updateDays = mutableListOf<Int>()
                for (i in 1..date) {
                    updateDays.add(i)
                }
                binding.dayPicker.setMaxValue(date - 1)
                binding.dayPicker.setAdapter(TimeWheelAdapter(updateDays, "日"))
                binding.dayPicker.setValue(day.substring(0, day.length - 1))
            }
        })
        binding.monthPicker.setOnValueChangedListener(object : OnValueChangeListener {
            override fun onValueChange(picker: WheelView, oldVal: String, newVal: String) {
                val year = binding.yearPicker.getCurrentItem()
                val month = binding.monthPicker.getCurrentItem()
                val day = binding.dayPicker.getCurrentItem()
                val selCalendar = Calendar.getInstance()
                selCalendar.set(Calendar.YEAR, year.substring(0, year.length - 1).toInt())
                selCalendar.set(Calendar.MONTH, month.substring(0, month.length - 1).toInt() - 1)
                selCalendar.set(Calendar.DATE, 1)
                selCalendar.roll(Calendar.DATE, -1)
                val date = selCalendar.get(Calendar.DATE)
                val updateDays = mutableListOf<Int>()
                for (i in 1..date) {
                    updateDays.add(i)
                }
                binding.dayPicker.setMaxValue(date)
                binding.dayPicker.setAdapter(TimeWheelAdapter(updateDays, "日"))
                binding.dayPicker.setValue(day.substring(0, day.length - 1))
            }
        })
        //设置点击dialog外部不消失
        //bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show()
    }
}

class BottomSheetAdapter :
    BaseQuickBindAdapter<BottomSheetEntity, QuickViewHolder>() {
    override fun onBindViewHolder(
        holder: QuickViewHolder,
        position: Int,
        item: BottomSheetEntity?
    ) {
        item?.let {
            holder.setText(R.id.tv_simple_content, item.content)
        }
    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup,
        viewType: Int
    ): QuickViewHolder {
        return QuickViewHolder(R.layout.widget_bottom_sheet_adapter, parent)
    }


}